﻿using Aspose.Cells;
using Common.Utility.AJ.Extension;
using Microsoft.Windows.Controls;
using Microsoft.WindowsAPICodePack.Dialogs;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.Record;
using NPOI.SS.Formula.Functions;
using NPOI.XSSF.UserModel;
using Stylet;
using SUT.PrintEngine.Utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Markup;
using WeighingRecord.Models;
using WeighingRecord.Services;
using WeighingRecord.Views;
using static WeighingRecord.ViewModels.WeightAccountViewModel;

namespace WeighingRecord.ViewModels
{
    public class WeightAccountViewModel : Screen
    {

        internal static readonly Dictionary<string, Func<object, IEnumerable<object>>> _filterMaps
                = new Dictionary<string, Func<object, IEnumerable<object>>>
            {
                {"wz",
                 (param)=>
                    {
                        return new BindableCollection<CustomerModel>(SQLDataAccess.LoadWz()
                            .Where(p=>!string.IsNullOrWhiteSpace(p.Name)).Distinct()
                            .Select(p=>new CustomerModel
                        {
                            Name = p.Name
                        }).ToArray());
                    }
                },
                {"ch",
                 (param)=>
                    {
                        return new BindableCollection<CustomerModel>(SQLDataAccess.LoadActiveCar(2)
                            .Where(p=>!string.IsNullOrWhiteSpace(p.PlateNo))
                            .Select(p=> new CustomerModel
                        {
                            Id = p.AutoNo,
                            Name = p.PlateNo,
                            Comment = p.Comment,
                            Valid = p.Valid,
                            Type = p.Driver,
                            Phone = p.DriverPhone
                        }));
                    }
                },
                {"by",
                 (param)=>
                    {
                        return new BindableCollection<CustomerModel>(SQLDataAccess.LoadByxValue($"By{param}")
                            .Where(p=>!string.IsNullOrWhiteSpace(p))
                            .Select(p=>new CustomerModel
                            {
                                Name = p
                            }));
                    }
                },
                {"fhdw",
                 (param)=>
                    {
                        return new BindableCollection<CustomerModel>(SQLDataAccess.LoadByxValue($"fhdw")
                            .Where(p=>!string.IsNullOrWhiteSpace(p))
                            .Select(p=>new CustomerModel
                            {
                                Name = p
                            }));
                    }
                },
                {"kh",
                 (param)=>
                    {
                        if ("0".Equals(param))
                        {
                            return new BindableCollection<CustomerModel>(SQLDataAccess.LoadActiveCustomer(2));
                        }
                        return new BindableCollection<CustomerModel>(SQLDataAccess.LoadByxValue($"Kh{param}")
                            .Where(p=>!string.IsNullOrWhiteSpace(p)).Select(p=>new CustomerModel
                            {
                                Name = p
                            }));
                    }
                },
                {"goodsSpec",
                 (param)=>
                    {
                        return new BindableCollection<CustomerModel>(SQLDataAccess.LoadGoodsSpec()
                            .Distinct().Where(p=>!string.IsNullOrWhiteSpace(p.Name))
                            .Select(p=> new CustomerModel
                        {
                            Name = p.Name
                        }).ToArray());
                    }
                }
            };

        public class GroupFieldItem
        {
            public string Name { get; set; }
            public string Column { get; set; }
            public bool Checked { get; set; }
            public Type ColumnDataType { get; set; }
            public IEnumerable<object> DropdownSource { get; set; }
            public bool FilterChecked { get; set; }
            public object SelectedItem { get; set; }
            public string SearchText { get; set; }

            public void InitFilter()
            {
                var hasMap = _filterMaps.Keys.Any(p => p == Column || Column.Contains(p));
                if (hasMap)
                {
                    var map = _filterMaps.FirstOrDefault(p => p.Key == Column || Column.Contains(p.Key));
                    var param = string.Empty;
                    if (map.Key == "by" || map.Key == "kh")
                    {
                        param = Column.Replace(map.Key, "").TryGetInt().ToString();
                    }

                    DropdownSource = map.Value.Invoke(param);
                }
            }
        }


        private static readonly log4net.ILog log = LogHelper.GetLogger();

        private IWindowManager windowManager;

        private string dateFilter; //日期筛选，0：本日 1：本月 2：自定义 ，3 近一年
        public string DateFilter
        {
            get
            {
                return dateFilter;
            }
            set
            {
                dateFilter = value;
                if (value.Equals("0"))
                {
                    StartDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                    EndDate = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").ToString()).AddSeconds(-1);
                }
                else if (value.Equals("1"))
                {
                    StartDate = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date;
                    EndDate = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date.AddMonths(1).AddSeconds(-1);
                }
                else if (value.Equals("3"))
                {
                    var now = DateTime.Now;
                    var lastYear = new DateTime(now.AddYears(-1).Year, 1, 1);

                    StartDate = lastYear;
                    var a = new DateTime(now.Year, 1, 1);
                    var b = a.AddSeconds(-1);
                    EndDate = b;
                }
            }
        }
        public DateTime? StartDate { get; set; } //自定义日期筛选的开始日期
        public DateTime? EndDate { get; set; } //自定义日期筛选的结束日期


        public BindableCollection<GroupFieldItem> StatisticalList { get; } //统计对象下拉列表


        public string SelectedStatisticalObj { get; set; }

        public BindableCollection<GroupFieldItem> SelectedItems { get; set; } //选择的显示字段

        public string StatusBar { get; set; }
        public Dictionary<string, string> TemplateFieldDic { get; set; } = new Dictionary<string, string>();
        public AppSettingsSection AppSection { get; } = (AppSettingsSection)ConfigurationManager.OpenExeConfiguration("衡七管家.exe").GetSection("appSettings");
        public Worksheet Worksheet { get; }
        public string WeighingUnit { get; }
        public List<WeighingRecordSumModel> WList { get; private set; } //从数据库中查询出的原始称重记录列表
        public DataTable RecordDT { get; private set; } //经过转换的称重记录表格，用来显示到列表、导出到excel

        public bool EnableQueryReport { get; set; } = false;
        public bool EnablePrintReport { get; set; } = false;
        public bool EnableExportReport { get; set; } = false;

        private bool selectAll;
        public bool SelectAll
        {
            get { return selectAll; }
            set
            {
                selectAll = value;

                //SelectedItems.Clear();

                //if (value)
                //{
                //    foreach (var item in TemplateFieldDic)
                //    {
                //        SelectedItems.Add(item.Value);
                //    }
                //}
            }
        }

        /// <summary>
        /// 这个用来存放当前表格的所有列顺序，每次执行查询重新赋值，后面导出和打印需要用这个判断显示合计字符串的列
        /// --阿吉 2023年6月20日19点24分
        /// </summary>
        private List<GroupFieldItem> _checkedFieldItems;

        public WeightAccountViewModel(IWindowManager windowManager)
        {
            this.windowManager = windowManager;
            _checkedFieldItems = new List<GroupFieldItem>();
            //初始化日期筛选选择本日
            DateFilter = "0";

            //初始化条件筛选下拉框内容列表
            StatisticalList = new BindableCollection<GroupFieldItem>();
            SelectedItems = new BindableCollection<GroupFieldItem>
        {
            new GroupFieldItem
            {
                Name = "总毛重",
                Checked = true,
                Column = "mz",
                ColumnDataType = typeof(double),
            },
            new GroupFieldItem
            {
                Name = "总皮重",
                Checked = true,
                Column = "pz",
                ColumnDataType = typeof(double),
            },new GroupFieldItem
            {
                Name = "总净重",
                Checked = true,
                Column = "jz",
                ColumnDataType = typeof(double),
            },new GroupFieldItem
            {
                Name = "总实重",
                Checked = true,
                Column = "sz",
                ColumnDataType = typeof(double),
            },new GroupFieldItem
            {
                Name = "总金额",
                Checked = true,
                Column = "je",
                ColumnDataType = typeof(double),
            },new GroupFieldItem
            {
                Name = "总单价",
                Checked = true,
                Column = "goodsprice",
                ColumnDataType = typeof(double),
            },new GroupFieldItem
            {
                Name = "总车次",
                Checked = true,
                Column = "count",
                ColumnDataType = typeof(int),
            }
        };

            WeighingUnit = AppSection.Settings["WeighingUnit"].Value;

            //根据过磅单初始化显示字段列表
            try
            {
                //打开过磅单模板
                Worksheet = new Workbook(Globalspace._weightFormTemplatePath).Worksheets[0];

                //设置查找区域：有内容的区域
                var range = Worksheet.Cells.MaxDisplayRange;
                string cellRange = range.RefersTo.Split('!')[1].Replace("$", "");
                string startCellName = cellRange.Split(':')[0];
                string endCellName = cellRange.Split(':')[1];
                CellArea area = CellArea.CreateCellArea(startCellName, endCellName);
                //查找规则
                FindOptions opts = new FindOptions();
                opts.LookInType = LookInType.Values;
                opts.LookAtType = LookAtType.Contains;
                opts.SetRange(area);

                Cell cell = null;

                var allFields = _filterMaps.Select(p => p.Key).ToArray();
                do
                {
                    // Search the cell contain value search within range
                    cell = Worksheet.Cells.Find("_", cell, opts);

                    // If no such cell found, then break the loop
                    if (cell == null)
                        break;
                    var cellStr = cell.Value.ToString();
                    //根据app.config和excel模版，读取字段放到DIC里，去掉打印日期字段

                    if (!TemplateFieldDic.ContainsKey(cellStr) && allFields.Any(p => p == cellStr || cellStr.Contains(p)))
                    {
                        var val = AppSection.Settings[cellStr].Value;
                        TemplateFieldDic.Add(cellStr, val);
                        var gItem = new GroupFieldItem
                        {
                            Name = val,
                            Column = cellStr.Replace("_", ""),
                            //// 目前默认都是字符串字段 --阿吉 2023年6月19日09点30分
                            ColumnDataType = typeof(string),
                        };

                        gItem.InitFilter();

                        StatisticalList.Add(gItem);
                    }


                } while (true);

            }
            catch (Exception e)
            {
                StatusBar = e.Message;
            }


            string rolePermission = SQLDataAccess.LoadLoginRolePermission(Globalspace._currentUserId);
            if (rolePermission != null)
            {
                if (rolePermission.Contains("查询报表")) EnableQueryReport = true;
                if (rolePermission.Contains("打印报表")) EnablePrintReport = true;
                if (rolePermission.Contains("导出报表")) EnableExportReport = true;
            }

            //初始化分页控件的页行数的大小
            SelectedPageSizeItems = PageSizeItems.FirstOrDefault();

        }

        public void QueryReport()
        {
            if (!StatisticalList.Any(p => p.Checked))
            {
                MessageBox.Show("请选择统计对象", "提示");
                return;
            }

            if (!SelectedItems.Any(p => p.Checked))
            {
                MessageBox.Show("请至少选择显示列", "提示");
                return;
            }

            //初始化SQL语句的参数，查询数据库得到初始数据

            string strStartDate = ((DateTime)StartDate).ToString("yyyy-MM-dd HH:mm:ss");
            string strEndDate = ((DateTime)EndDate).ToString("yyyy-MM-dd HH:mm:ss");


            var maxAbnormalData = Common.Utility.SettingsHelper.ZXWeighingRecordSettings.Settings["MaxAbnormalData"]?.Value.TryGetDecimal() ?? 100000m;
            WList = SQLDataAccess.LoadWeighingAccountGroup(strStartDate, strEndDate,
                StatisticalList.Where(p => p.Checked),maxAbnormalData);

            //处理数据，放入DataTable中
            var dt = new DataTable("WeighingRecord");

            //修改列类型
            //var decimalColNames = new string[] { "总毛重", "总皮重", "总净重", "总实重", "总车次" };

            _checkedFieldItems = StatisticalList.Where(p => p.Checked).Union(SelectedItems
                .Where(p => p.Checked)).ToList();
            foreach (var item in WList)
            {
                var row = dt.NewRow();
                var props = item.GetType().GetRuntimeProperties();
                foreach (var col in _checkedFieldItems)
                {
                    if (!dt.Columns.Contains(col.Name))
                    {
                        dt.Columns.Add(col.Name, col.ColumnDataType);
                    }

                    var prop = props.FirstOrDefault(p => p.Name.Equals(col.Column, StringComparison.OrdinalIgnoreCase));
                    var colVal = prop?.GetValue(item);
                    row[col.Name] = colVal == null ? DBNull.Value : colVal;
                }

                dt.Rows.Add(row);
            }


            DataCount = WList.Count;//数据总数
            //Pages = (DataCount + PageCount - 1);
            //把datatable set到属性RecordDT
            RecordDT = dt;
        }

        public void PrintReport()
        {
            if (RecordDT == null || RecordDT.Rows.Count == 0)
            {
                MessageBox.Show("当前统计列表为空", "提示");
                return;
            }

            //设置列宽
            var columnWidths = new List<double>();
            var colCount = RecordDT.Columns.Count;
            var _kh = AppSection.Settings["_kh"].Value;
            var _ch = AppSection.Settings["_ch"].Value;
            var array = new string[] { _kh, _ch };
            for (int i = 0; i < colCount; i++)
            {
                columnWidths.Add(array.Contains(RecordDT.Columns[i].ColumnName)
                    ? 80 : 70);
            }
            var ht = new AccountHeaderTemplate();
            var headerTemplate = XamlWriter.Save(ht);
            var companyName = AppSection.Settings["CompanyName"]?.Value ?? "";
            headerTemplate = headerTemplate
                .Replace("@StartDate", ((DateTime)StartDate).ToString("yyyy/MM/dd HH:mm:ss"))
                .Replace("@EndDate", ((DateTime)EndDate).ToString("yyyy/MM/dd HH:mm:ss"))
                .Replace("@WeighingUnit", WeighingUnit)
                .Replace("称重统计表", $"{companyName}-称重统计表");

            var tempTable = CreateTableForExportOrPrint();

            var printControl = PrintControlFactory.Create(tempTable, columnWidths, headerTemplate);
            printControl.ShowPrintPreview();
        }

        private DataTable CreateTableForExportOrPrint()
        {
            var sumColumnNames = new Dictionary<string, string>
                {
                    { "总毛重",nameof(WeighingRecordSumModel.Mz)},
                    { "总皮重",nameof(WeighingRecordSumModel.Pz)},
                    {"总净重",nameof(WeighingRecordSumModel.Jz) },
                    {"总实重",nameof(WeighingRecordSumModel.Sz) },
                    {"总金额",nameof(WeighingRecordSumModel.Je) },
                    {"总单价",nameof(WeighingRecordSumModel.GoodsPrice) },
                    {"总车次",nameof(WeighingRecordSumModel.Count) },
                };

            // 增加合计行 --阿吉 2023年6月20日18点21分
            var tempTable = RecordDT.DefaultView.ToTable();
            var sumRow = tempTable.NewRow();
            var paramExp = System.Linq.Expressions.Expression.Parameter(typeof(WeighingRecordSumModel), "p");
            IQueryable<WeighingRecordSumModel> source = WList.AsQueryable();
            foreach (DataColumn column in tempTable.Columns)
            {
                if (sumColumnNames.Keys.Contains(column.Caption))
                {
                    var field = sumColumnNames[column.Caption];
                    var propInfo = typeof(WeighingRecordSumModel)
                        .GetRuntimeProperties()
                        .FirstOrDefault(p => p.Name.Equals(field, StringComparison.OrdinalIgnoreCase));
                    var columnExpr = System.Linq.Expressions
                        .Expression.Property(paramExp, propInfo);
                    if (field.Equals(nameof(WeighingRecordSumModel.Count)))
                    {
                        var lambda = System.Linq.Expressions.
                        Expression.Lambda<Func<WeighingRecordSumModel, int>>(columnExpr, paramExp);
                        sumRow[column.Caption] = source.Sum(lambda);
                    }
                    else
                    {
                        var lambda = System.Linq.Expressions.
                        Expression.Lambda<Func<WeighingRecordSumModel, decimal>>(columnExpr, paramExp);
                        sumRow[column.Caption] = source.Sum(lambda);
                    }

                }
            }

            //计算需要显示合计字符串的列
            var firstSumCol = SelectedItems.Where(p => p.Checked).FirstOrDefault()?.Name;
            var firstSumColIndex = _checkedFieldItems.FindIndex(p => p.Name == firstSumCol);
            if (firstSumColIndex == -1)
            {
                firstSumColIndex = 1;
            }
            sumRow[firstSumColIndex - 1] = "合计：";
            tempTable.Rows.Add(sumRow);


            return tempTable;
        }

        public void ExportReport()
        {
            try
            {
                if (RecordDT == null)
                {
                    StatusBar = "当前统计列表为空";
                    return;
                }

                //使用DataTable数据新建excle表格
                Workbook workbook = new Workbook();
                Worksheet worksheet = workbook.Worksheets[0];
                worksheet.Name = "称重统计";

                ImportTableOptions importOptions = new ImportTableOptions();
                importOptions.IsFieldNameShown = true;
                importOptions.IsHtmlString = true;

                var tempTable = CreateTableForExportOrPrint();

                worksheet.Cells.ImportData(tempTable, 0, 0, importOptions);

                #region 增加表头、格式

                Aspose.Cells.Style blodStyle = workbook.CreateStyle();
                blodStyle.Font.IsBold = true;
                StyleFlag flag = new StyleFlag();
                flag.FontBold = true;

                Aspose.Cells.Style headerStyle = workbook.CreateStyle();
                headerStyle.Font.IsBold = true;
                headerStyle.Font.Size = 16;
                headerStyle.HorizontalAlignment = TextAlignmentType.Center;

                worksheet.Cells.Rows[0].ApplyStyle(blodStyle, flag);

                worksheet.Cells.InsertRows(0, 3);

                worksheet.Cells.Merge(0, 0, 1, 8);
                var companyName = AppSection.Settings["CompanyName"]?.Value ?? "";
                worksheet.Cells["A1"].PutValue($"{companyName}-称重统计表");
                worksheet.Cells["A1"].SetStyle(headerStyle);
                worksheet.Cells["A2"].PutValue("统计日期");
                worksheet.Cells["A2"].SetStyle(blodStyle);
                worksheet.Cells.Merge(1, 1, 1, 5);
                worksheet.Cells["B2"].PutValue(((DateTime)StartDate).ToString("yyyy/MM/dd HH:mm:ss") + " ~ " + ((DateTime)EndDate).ToString("yyyy/MM/dd HH:mm:ss"));
                worksheet.Cells["G2"].PutValue("重量单位");
                worksheet.Cells["G2"].SetStyle(blodStyle);
                worksheet.Cells["H2"].PutValue(WeighingUnit);

                worksheet.AutoFitColumns();
                #endregion



                workbook.Save(Globalspace._weighingRecordTempPath, SaveFormat.Xlsx);

                //删掉aspose的试用版信息，删掉临时文件
                XSSFWorkbook book;
                using (FileStream file = new FileStream(Globalspace._weighingRecordTempPath, FileMode.Open, FileAccess.Read))
                {
                    book = new XSSFWorkbook(file);
                }
                // book.RemoveSheetAt(1);
                File.Delete(Globalspace._weighingRecordTempPath);

                //打开保存文件对话框，保存称重记录
                CommonSaveFileDialog dialog = new CommonSaveFileDialog();
                dialog.DefaultFileName = "称重统计_" + DateTime.Now.ToString("yyyyMMdd");
                dialog.DefaultExtension = "xlsx";
                dialog.AlwaysAppendDefaultExtension = true;
                dialog.Filters.Add(new CommonFileDialogFilter("Excel 工作簿", ".xlsx"));

                if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    FileStream file = new FileStream(dialog.FileName, FileMode.Create);
                    book.Write(file);
                    file.Close();
                    book.Close();
                    StatusBar = "导出成功！称重统计文件路径：" + dialog.FileName;
                }
            }
            catch (Exception e)
            {
                log.Info($"ExportReport error:{e.Message}");
            }
        }


        #region 分页逻辑以及属性

        /// <summary>
        /// 索引信息集合
        /// </summary>
        public ObservableCollection<WeighingRecord.Models.Custom.PagerHandle> Indexs { get; set; } = new ObservableCollection<Models.Custom.PagerHandle>();

        public System.Windows.Style LeftStyle { get; set; } = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"];

        public System.Windows.Style RightStyle { get; set; } = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"];

        public ObservableCollection<WeighingRecord.Models.Custom.ComboItem> PageSizeItems { get; set; } = new ObservableCollection<Models.Custom.ComboItem>
        {
            new Models.Custom.ComboItem(){ Name="100条/页", Value=100 },
            new Models.Custom.ComboItem(){ Name="500条/页", Value=500 },
            new Models.Custom.ComboItem(){ Name="1000条/页", Value=1000 },
            new Models.Custom.ComboItem(){ Name="2000条/页", Value=2000 },
            new Models.Custom.ComboItem(){ Name="5000条/页", Value=5000 },
            //new Models.Custom.ComboItem(){ Name="100条/页", Value=100 },
            //new Models.Custom.ComboItem(){ Name="200条/页", Value=200 }
            //new Models.Custom.ComboItem(){ Name="300条/页", Value=300 },
            //new Models.Custom.ComboItem(){ Name="400条/页", Value=400 },
            //new Models.Custom.ComboItem(){ Name="500条/页", Value=500 },
            //new Models.Custom.ComboItem(){ Name="1000条/页", Value=1000 }
        };

        WeighingRecord.Models.Custom.ComboItem _SelectedPageSizeItems;
        public WeighingRecord.Models.Custom.ComboItem SelectedPageSizeItems
        {
            get
            {
                return _SelectedPageSizeItems;
            }
            set
            {
                if (value != null)
                {
                    _SelectedPageSizeItems = value;
                    PageCount = int.Parse(_SelectedPageSizeItems.Value.ToString());
                }
            }
        }

        /// <summary>
        /// 当前选中的索引信息
        /// </summary>
        public int CurrentIndex { get; set; } = 1;
        /// <summary>
        /// 页总数
        /// </summary>
        public int Pages { get; set; }
        /// <summary>
        /// 有效的索引按钮个数，不包含（...，最有一页这2个按钮）
        /// </summary>
        public int IndexButs { get; set; } = 3;
        /// <summary>
        /// 一页显示的行数
        /// </summary>
        public int PageCount { get; set; } = 1;
        /// <summary>
        /// 数据的总数
        /// </summary>
        public int DataCount { get; set; }


        public void LeftSide(object indexStr)
        {
            LeftStyle = (System.Windows.Style)Application.Current.Resources["YellowStyle"];
            RightStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"];

            var moveIndex = CurrentIndex - 1;
            if (moveIndex < 1) return;

            CurrentIndex = moveIndex;

            SetBtns();
            SelectedPage(moveIndex.ToString());

        }

        public void RightSide(object indexStr)
        {
            var moveIndex = CurrentIndex + 1;
            if (moveIndex > Pages) return;

            RightStyle = (System.Windows.Style)Application.Current.Resources["YellowStyle"];
            LeftStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"];

            CurrentIndex = moveIndex;

            SetBtns();
            SelectedPage(moveIndex.ToString());

        }

        public void SelectedPage(object indexStr)
        {
            string str = indexStr.ToString();

            if (string.IsNullOrEmpty(str)) return;

            if (str != "...")
            {
                CurrentIndex = int.Parse(str);
            }

            if (str == "...")
            {
                var maxIndex = Indexs.Where(p => p.IndexStr != "..." && p.IndexStr != Pages.ToString()).Max(p => int.Parse(p.IndexStr));
                CurrentIndex = maxIndex;
                SetBtns();
            }
            else
            {
                var indexInfo = Indexs.FirstOrDefault(p => p.IndexStr == str);

                Indexs.ToList().ForEach(e => { e.ControlStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"]; });

                indexInfo.ControlStyle = (System.Windows.Style)Application.Current.Resources["YellowStyle"];

                QueryReport();
                if (CurrentIndex == Pages)
                {
                    SetBtns();
                }
            }

        }

        private void SetBtns()
        {
            Indexs.Clear();

            if (CurrentIndex < 1 || CurrentIndex > Pages) return;

            if (Pages <= IndexButs)
            {
                for (int i = 1; i <= Pages; i++)
                {
                    if (i == CurrentIndex)
                    {
                        Indexs.Add(new Models.Custom.PagerHandle() { IndexStr = i.ToString(), ControlStyle = (System.Windows.Style)Application.Current.Resources["YellowStyle"] });
                        continue;
                    }
                    Indexs.Add(new Models.Custom.PagerHandle() { IndexStr = i.ToString(), ControlStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"] });
                }

            }
            else
            {
                int i = CurrentIndex;

                for (; i <= Pages; i++)
                {
                    if (i - CurrentIndex >= IndexButs) break;

                    if (i == CurrentIndex)
                    {
                        Indexs.Add(new Models.Custom.PagerHandle() { IndexStr = i.ToString(), ControlStyle = (System.Windows.Style)Application.Current.Resources["YellowStyle"] });
                        continue;
                    }
                    Indexs.Add(new Models.Custom.PagerHandle() { IndexStr = i.ToString(), ControlStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"] });
                }
                if (i < Pages)
                {
                    Indexs.Add(new Models.Custom.PagerHandle() { IndexStr = "...", ControlStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"] });
                    Indexs.Add(new Models.Custom.PagerHandle() { IndexStr = Pages.ToString(), ControlStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"] });
                }
                else if (Indexs.Count < IndexButs)//如果没有预定的IndexButs个按钮，那么就要补齐少的
                {
                    int minIdex = Indexs.Min(p => int.Parse(p.IndexStr));
                    for (int j = Indexs.Count; j < IndexButs; j++)
                    {
                        minIdex--;
                        Indexs.Insert(0, new Models.Custom.PagerHandle() { IndexStr = (minIdex).ToString(), ControlStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"] });
                    }
                }
            }
        }

        public void Query()
        {
            CurrentIndex = 1;
            QueryReport();
            SetBtns();
        }

        #endregion 


        public void TableSorted(object sender, System.Windows.Controls.DataGridColumnEventArgs e)
        {
            //if (e.Column.SortDirection ==  null)
            //{
            //    return;
            //}

            //var colName = e.Column.Header.ToString();

            //var dic = e.Column.SortDirection.GetValueOrDefault() == System.ComponentModel.ListSortDirection.Ascending ? "ASC" : "DESC";

            //RecordDT.DefaultView.Sort = $"{colName} {dic}";

            //RecordDT = RecordDT.DefaultView.ToTable();

        }
    }
}
